<?php
/**
 * lyx
 * ============================================================================
 * * 版权所有 2018-2027 沈阳隆原兴网络科技有限公司，并保留所有权利。
 * 网站地址: https://gitee.com/150400249808/tpshop5_version
 * ----------------------------------------------------------------------------
 * 小程序首页定制化功能展示
 * ============================================================================
 * $Author: Mike 2018-08-28
 */

namespace app\api\controller;

use think\Db;

class MiniHome extends Base
{
    /**
     * 商品轮播图列表
     */
    public function shopAdList()
    {
        $start_time = strtotime(date('Y-m-d H:00:00'));
        $end_time = strtotime(date('Y-m-d H:00:00'));
        $where = array("a.pid" => 500);

        $domain = C('domain_url');

        $adv = M("ad")->alias('a')->field(array('a.ad_link', 'a.ad_name', "concat('$domain',a.ad_code) as ad_code", 'a.media_type', 'a.pid', 'b.is_case'))
            ->join('__GOODS__ b', 'a.ad_link = b.goods_id', 'LEFT')
            ->where(" a.enabled=1 and a.start_time< $start_time and a.end_time > $end_time")->where($where)
            ->limit(20)->select();

        $json = array(
            'status' => 1,
            'msg' => '获取成功',
            'result' => array(
                'ad' => $adv
            ),
        );
        $this->ajaxReturn($json);
    }

    /**
     * 小程序首页定制化数据
     */
    public function minHome()
    {
        $list = Db::name('mini_template')->where('is_show', 1)->field('id,template_name,template_json,update_time')->find();
        if ($list == false) {
            $this->ajaxReturn(['status' => 0, 'msg' => '没有设置首页']);
        }
//        dump($list['template_json']);
        $json_html = json_decode(htmlspecialchars_decode($list['template_json']), JSON_UNESCAPED_UNICODE);
//        dump($json_html);
        $result = $this->minDataFilter($json_html);
        $result['title'] = $list['template_name'];
        $this->ajaxReturn(['status'=>1,'msg'=>'获取配置页面成功','result'=>$result]);
    }

    private function minDataFilter($data)
    {
        $retData = [];
        foreach ($data as $key => $value) {

            if ($key == 'is_notice') {
                $retData['config']['is_notice'] = $value;
            } elseif ($key == 'is_header') {
                $retData['config']['is_header'] = $value;
            } elseif ($key == 'is_footer') {
                $retData['config']['is_footer'] = $value;
            } elseif ($key == 'is_search') {
                $retData['config']['is_search'] = $value;
            } else {
                if($key != 'search_id'){
                    $funret = $this->minBodyFilter($value);
                    $retData['body'][$funret['div_order']] = $funret;
                }
            }
        }

        return $retData;
    }

    /**
     * 主题数据过滤
     */
    private function minBodyFilter($data)
    {
        //  0海报    1轮播广告   2快捷入口   3商品列表   4橱窗    5文本导航   6营销活动   7优惠券    8搜索栏    9店铺头部   10公告    11底部菜单
        $retData = [];
        $domain = C('domain_url');
        switch ($data['block_type']) {
            case 0:
                parse_str($data['url'], $arr);
                $retData = $data;
                $retData['model'] = $arr['a'];
                $retData['id'] = $arr['id'];
                $retData['pic'] = $domain . $retData['pic'];
                break;
            case 1:
                $retData = $this->minBodyNavFilter('轮播广告', $data);
                break;
            case 2:
                $retData = $this->minBodyNavFilter('快捷入口', $data);
                break;
            case 3:
                $retData = $this->minBodyGoodsFilter('产品列表', $data);
                break;
            case 4:
                $retData = $this->minBodyNavFilter('橱窗', $data);
                break;
            case 5:
                parse_str($data['url'], $arr);
                $retData = $data;
                $retData['model'] = $arr['a'];
                $retData['id'] = $arr['id'];
                break;
            case 8:
                $retData = $data;
                $retData['div_order'] = 0;
                break;
            case 10:
                 $retData = $this->minBodyNavFilter('通知', $data);
                break;
        }

        return $retData;

    }

    /**
     * 过滤rul地址返回新的格式
     */
    private function minBodyNavFilter($name, $data)
    {
        $domain = C('domain_url');
        $data['template_name'] = $name;
        $notice_type = false;
        foreach ($data['nav'] as $key => $val) {
            parse_str($val['url'], $arr);
            if (!empty($val['title_name'])) {
                $ma[] = array('pic' => $domain . $val['pic'], 'model' => $arr['a'], 'id' => $arr['id'], 'title_name' => $val['title_name']);
            }elseif (!empty($val['notice_title'])){
                $notice_type = true;
                $ma[] = array('model' => $arr['a'], 'id' => $arr['id'], 'notice_title' => $val['notice_title'],'notice_info' => $val['notice_info']);
            }else {
                $ma[] = array('pic' => $domain . $val['pic'], 'model' => $arr['a'], 'id' => $arr['id']);
            }
        }
        if($notice_type){
            $data['notice_pic'] =  $domain.$data['notice_pic'];
        }
        $data['nav'] = $ma;
        return $data;
    }

    /**
     * 产品列表过滤
     */
    private function minBodyGoodsFilter($name, $data)
    {
        $domain = C('domain_url');
        $data['template_name'] = $name;
        foreach ($data['nav'] as $key => $val) {
            if (is_array($val['sql_where'])) {
                $sqlWhere = $val['sql_where'];
                if (!empty($sqlWhere['min_price']) && !empty($sqlWhere['max_price'])) {
                    $map['shop_price'] = array('between',array($sqlWhere['min_price'],$sqlWhere['max_price']));
                }
                if(!empty($sqlWhere['goods'])){
                    $map['goods_id'] = array('in',$sqlWhere['goods']);
                }
                if(!empty($sqlWhere['ids'])){
                    $map['cat_id'] = array('in',$sqlWhere['ids']);
                }

                $map1 = '';
                if(!empty($sqlWhere['label'])){
                    $map1 =$sqlWhere['label'].'=1 ';
                }

                switch ($sqlWhere['order']){
                    case 0: $order = 'sales_sum desc';
                        break;
                    case 1: $order = 'sales_num asc';
                        break;
                    case 2: $order = 'shop_price desc';
                        break;
                    case 3: $order = 'shop_price asc';
                        break;
                    case 4: $order = 'last_update desc';
                        break;
                    case 5: $order = 'last_update asc';
                        break;
                    default:$order = 'id asc';
                }

            }
            $goodsList = Db::name('goods')->field("goods_id,cat_id,goods_sn,goods_name,goods_remark,market_price,shop_price,comment_count,sales_sum,concat('$domain',original_img) as original_img,click_count,is_case")->where($map)->where($map1)->limit($data['num'])->order($order)->select();
            $datx['tab_title'] = $val['tab_title'];
            $datx['goodsList'] = $goodsList;
            $nav[] = $datx;
        }
        $data['nav'] = $nav;
        $data['selectedId'] = 0;
        return $data;
    }


    /**
     * 小程序自定义分类列表【树形菜单】
     */

    public function getMenuTree(){
        $list = Db::name('mini_category')->where('is_show',1)->order('parent_id_path asc,sort_order desc')->field('id,mobile_name,name,parent_id,parent_id_path,level,sort_order,model,model_id')->select();
        $tree = build_tree($list,0);
        if($tree){
            $this->ajaxReturn(['status' => 1, 'msg' => '获取数据成功','result' => $tree]);
        }else{
            $this->ajaxReturn(['status' => -1, 'msg' => '添加失败']);
        }
    }

    public function createMiniQr(){
        $qrcode = new \app\common\logic\UsersLogic();
        $ShareLink = "http://{$_SERVER['HTTP_HOST']}".$qrcode->createMiniQr();
        echo $ShareLink;
    }
}